package com.winai.launcher.view.set;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.winai.launcher.BroadcastReceiver.SystemEventReceiver;
import com.winai.launcher.R;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.PicassoLoadUtils;
import com.winai.launcher.utils.MathUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2019/11/15 0015
 * 描述：设置声音
 */
@SuppressLint("SetTextI18n")
public class SetVoiceActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.iv_voice)
    ImageView ivVoice;
    @BindView(R.id.seek_voice)
    SeekBar seekVoice;
    @BindView(R.id.switch_keyTone)
    Switch switchKeyTone;
    @BindView(R.id.str_title)
    TextView strTitle;

    /*变量*/
    private int voiceNum = 0;
    private AudioManager mAudioManager;
    private final int PERMISSION_RESULT = 0x0001;
    private boolean checked = false;//开关按键提示音


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_voice);
//        setStatusBar(true, true, R.color.colorWhite);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        /*initPermission();*/
        initObject();
        initListener();
        updateVoice();
    }


    /**
     * 说明：勿扰权限
     */
    private void initPermission() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !notificationManager.isNotificationPolicyAccessGranted()) {
            startActivity(new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS));
        }
    }

    private void initObject() {
        String titleName = getIntent().getStringExtra("titleName");
        strTitle.setText(titleName);
        voiceNum = getIntent().getIntExtra("voiceNum", 0);

        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (mAudioManager != null) {
            int currentVolume = SystemEventReceiver.mIndex;
            if (currentVolume == 0) {
                currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            }
            int streamMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//最大值15。
            voiceNum = (int) MathUtils.divide(currentVolume * 100, streamMaxVolume, 0);
        }
        if (voiceNum == 0) {
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_silence_green, ivVoice);
        } else {
            PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_voice_green, ivVoice);
        }
        seekVoice.setProgress(voiceNum);

        /*获取按键音是否开启*/
        int anInt = Settings.System.getInt(getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 0);
        switchKeyTone.setChecked(anInt == 1);
    }

    private void initListener() {
        seekVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int streamMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//最大值15。
                double divide = MathUtils.divide(progress * streamMaxVolume, 100, 0);//7.5
                double finalDivide = MathUtils.roundHalfUp(divide + "", 0);//四舍五入,8
                if (finalDivide != 0) {
                    //设置音量
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) finalDivide, 0);
                }
                voiceNum = (int) MathUtils.divide((int) finalDivide * 100, streamMaxVolume, 0);

                if (progress == 0) {
                    PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_silence_green, ivVoice);
                } else {
                    PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_voice_green, ivVoice);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                int currentVolume = SystemEventReceiver.mIndex;
                if (progress == 0) {
                    //减小音量到0
                    for (int i = 0; i < currentVolume; i++) {
                        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0);
                    }
                    PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_silence_green, ivVoice);
                }
            }
        });
        switchKeyTone.setOnCheckedChangeListener((buttonView, isChecked) -> {
            checked = isChecked;
            //设置系统声音
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.System.canWrite(mContext)) {
                    Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                    intent.setData(Uri.parse("package:" + mContext.getPackageName()));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    mContext.startActivity(intent);
                } else {
                    //有了权限，具体的动作
                    toggleSoundEffects(isChecked);
                }
            }
        });
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.CHANGE_VOICE_RECEIVER:
                        updateVoice();
                        break;
                }
            }
        });
    }

    private void updateVoice() {
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (mAudioManager != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    /*得到比例转换值，然后展示出来*/
                    int currentVolume = SystemEventReceiver.mIndex;
                    boolean muted = SystemEventReceiver.muted;
                    int streamMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//最大值7。
                    voiceNum = (int) MathUtils.divide(currentVolume * 100, streamMaxVolume, 0);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (muted || voiceNum == 0) {
                                PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_silence_green, ivVoice);
                                seekVoice.setProgress(0);
                            } else {
                                PicassoLoadUtils.getInstance().picassoLoadNoPlaceholder(R.mipmap.icon_voice_green, ivVoice);
                                seekVoice.setProgress(voiceNum);
                            }
                        }
                    });
                }
            }).start();
        }
    }

    /**
     * 说明：开关按键提示音
     */
    private void toggleSoundEffects(boolean isChecked) {
        Settings.System.putInt(mContext.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, isChecked ? 1 : 0);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        if (mAudioManager != null) {
            /*系统提示音设置*/
            if (isChecked) {
                mAudioManager.loadSoundEffects();
            } else {
                mAudioManager.unloadSoundEffects();
            }
        }
    }

    /**
     * 说明：切换静音
     */
    private void toggleVoice() {
        boolean muteFlag = mAudioManager.isStreamMute(AudioManager.STREAM_MUSIC);//获取当前音乐多媒体是否静音
        if (muteFlag) {
            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);//取消静音
        } else {
            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE, 0);//设为静音
        }
        updateVoice();
        GlobalPublisher.Notify(GlobalPublisher.CHANGE_VOICE, voiceNum);
    }

    @OnClick({R.id.iv_back, R.id.iv_home, R.id.iv_voice})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_home:
                //模拟HOME
                Intent it = new Intent(Intent.ACTION_MAIN);
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                it.addCategory(Intent.CATEGORY_HOME);
                mContext.startActivity(it);
                break;
            case R.id.iv_voice:
                toggleVoice();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_RESULT) {
            switch (permissions[0]) {
                case Manifest.permission.CAMERA:
                    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        //获取权限成功
                        ToastKs.show(mContext, "权限获取成功");
                        toggleSoundEffects(checked);
                    } else {
                        ToastKs.show(mContext, "必须同意此权限");
                    }
                    break;
            }
        }
    }
}
